package com.yonyou.gmmc.service.wechatpush.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.InputStreamBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpClientUtil {
	
private static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);
	
	/**
	*
	* httpclient-get
	* @date 2016年12月21日
	* @param url
	* @return
	*/
	public static String sendGetRequest(String url) {
        CloseableHttpClient client = null;
        CloseableHttpResponse res = null;
        try {
            client = HttpClients.createDefault();
            RequestConfig requestConfig = RequestConfig.custom().
                    setSocketTimeout(5000).setConnectTimeout(5000).build();//设置请求和传输超时时间
            
            //创建一个POST请求
            HttpGet httpGet = new HttpGet(url);
            httpGet.setConfig(requestConfig);
            // 执行get请求.    
            res = client.execute(httpGet);
            String resultStr = EntityUtils.toString(res.getEntity(), "UTF-8");
            logger.info(resultStr);
            return resultStr;
        } catch (Exception e) {
            logger.error(e.getMessage());
        } finally {
            if (res != null) {
                try {
                    res.close();
                } catch (IOException e) {
                }
            }
            if (client != null) {
                try {
                    client.close();
                } catch (IOException e) {
                }
            }
        }
        return null;
	}
	
	/**
	*
	* httpclient-post
	* @date 2016年12月21日
	* @param url
	* @param jsonBody
	* @return
	*/
	public static String sendPostRequest(String url, String jsonBody){
        CloseableHttpClient client = null;
        CloseableHttpResponse res = null;
        try {
            client = HttpClients.createDefault();
            RequestConfig requestConfig = RequestConfig.custom().
                    setSocketTimeout(5000).setConnectTimeout(5000).build();//设置请求和传输超时时间
            
            //创建一个POST请求
            HttpPost post = new HttpPost(url);
            post.setConfig(requestConfig);
            StringEntity s = new StringEntity(jsonBody, "UTF-8");
            s.setContentEncoding("UTF-8");
            s.setContentType("application/json;charset=UTF-8");
            post.setEntity(s);
            res = client.execute(post);
            logger.info("sendJsonMsgPost ok ");
            String resultStr = EntityUtils.toString(res.getEntity(), "UTF-8");
            logger.info(resultStr);
            return resultStr;
        } catch (Exception e) {
            logger.error(e.getMessage());
        } finally {
            if (res != null) {
                try {
                    res.close();
                } catch (IOException e) {
                }
            }
            if (client != null) {
                try {
                    client.close();
                } catch (IOException e) {
                }
            }
        }
        return null;
	}
	
    /**
    *
    * httpclient-put
    * @date 2016年12月22日
    * @param url
    * @param jsonBody
    * @return
    * @throws Exception
    */
    public static String sendPutRequest (String url, String jsonBody) throws Exception{
        CloseableHttpClient client = null;
        CloseableHttpResponse res = null;
        try {
            client = HttpClients.createDefault();
            RequestConfig requestConfig = RequestConfig.custom().
                    setSocketTimeout(5000).setConnectTimeout(5000).build();//设置请求和传输超时时间
            //创建一个PUT请求
            HttpPut put = new HttpPut(url);
            put.setConfig(requestConfig);
            StringEntity s = new StringEntity(jsonBody, "UTF-8");
            s.setContentEncoding("UTF-8");
            s.setContentType("application/json;charset=UTF-8");
            put.setEntity(s);
            res = client.execute(put);
            
            if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                logger.info("sendPutRequest ok ");
                HttpEntity entity = res.getEntity();
                if (entity != null) {  
                    String resultStr = EntityUtils.toString(entity, "UTF-8");
                    logger.info(resultStr);
                    return resultStr;
                }  
            } else {
                HttpEntity entity = res.getEntity();
                if (entity != null) {  
                    String resultStr = EntityUtils.toString(entity, "UTF-8");
                    logger.info("sendPutRequest fail ");
//                    logger.info(resultStr);
                    return resultStr;
                }  
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw e;
        } finally {
            if (res != null) {
                try {
                    res.close();
                } catch (IOException e) {
                }
            }
            if (client != null) {
                try {
                    client.close();
                } catch (IOException e) {
                }
            }
        }
        return null;
    }
    
    /**
    *
    * @author LiuJun
    * postMedia
    * @date 2016年12月26日
    * @param url
    * @param filePath
    * @return
    * @throws Exception
    */
    public static String postMedia(String url,String filePath,String filename) throws Exception {
        CloseableHttpClient client = null;
        CloseableHttpResponse resp = null;
        try {
            client = HttpClients.createDefault();
            HttpPost post = new HttpPost(url);
//            FileBody fb = new FileBody(new File(filePath));
            
            ByteArrayBody byteArrayBody = new ByteArrayBody(getFileByteArray(filePath),filename);
            //文件上传 -基于表单的形式 写法
            HttpEntity reqEntity = MultipartEntityBuilder
                        .create().addPart("media", byteArrayBody).build();
            post.setEntity(reqEntity);
            resp = client.execute(post);
            int sc = resp.getStatusLine().getStatusCode();
            if(sc>=200&&sc<300) {
                String result = EntityUtils.toString(resp.getEntity());
                return result;
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw e;
        } finally {

            try {
                if(client!=null) client.close();
            } catch (IOException e) {
            }
            try {
                if(resp!=null) resp.close();
            } catch (IOException e) {
            }

            
            
        }
        return null;
    }
    public static String postMedia(String url,String fileUrl) throws Exception {
        CloseableHttpClient client = null;
        CloseableHttpResponse resp = null;
        try {
            client = HttpClients.createDefault();
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60*1000).setConnectTimeout(120*1000).build();
            HttpPost post = new HttpPost(url);
            post.setConfig(requestConfig);
//            FileBody fb = new FileBody(new File(filePath));
            
            ByteArrayBody byteArrayBody = new ByteArrayBody(getFileByteArray(fileUrl),"tempJpg.jpg");
            //文件上传 -基于表单的形式 写法
            HttpEntity reqEntity = MultipartEntityBuilder
                        .create().addPart("image", byteArrayBody).build();
            post.setEntity(reqEntity);
            resp = client.execute(post);
            int sc = resp.getStatusLine().getStatusCode();
            if(sc>=200&&sc<300) {
                String result = EntityUtils.toString(resp.getEntity());
                return result;
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw e;
        } finally {

            try {
                if(client!=null) client.close();
            } catch (IOException e) {
            }
            try {
                if(resp!=null) resp.close();
            } catch (IOException e) {
            }

            
            
        }
        return null;
    }
    
    public static byte[] getFileByteArray(String filePath) throws Exception {
        InputStream inputStream = null;
        ByteArrayOutputStream output = null;
        try {
            URL urlTemp = new URL(filePath);
            HttpURLConnection httpConn = (HttpURLConnection) urlTemp.openConnection();

            httpConn.connect();
            inputStream = httpConn.getInputStream();

            output = new ByteArrayOutputStream();
            byte[] buffer = new byte[4096];
            int n = 0;
            if(inputStream != null){
            	n = inputStream.read(buffer);
            }
            while (-1 != n) {
                output.write(buffer, 0, n);
            }
            return output.toByteArray();
        } catch (Exception e) {
//        	logger.info("---url="+filePath+e.getMessage());
            logger.error(e.getMessage());
            throw e;

        } finally {
            try {
                if (inputStream != null) inputStream.close();
            } catch (Exception e) {
            }
            try {
                if (output != null) output.close();
            } catch (Exception e) {

            }

        }

    }

}
